package beikai.com.assistant.service.impl;

import beikai.com.assistant.common.domain.params.VillageDetailParams;
import beikai.com.assistant.common.exception.EleException;
import beikai.com.assistant.common.util.NumberUtil;
import beikai.com.assistant.common.util.R;
import beikai.com.assistant.dao.mapper.VillageDetailMapper;
import beikai.com.assistant.dao.model.VillageDetailModel;
import beikai.com.assistant.service.IVillageDetailService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * <p>
 * 小区杂费名目 服务实现类
 * </p>
 *
 * @author beikai
 * @since 2021-12-19
 */
@Service
@Slf4j
public class VillageDetailServiceImpl extends ServiceImpl<VillageDetailMapper, VillageDetailModel> implements IVillageDetailService {

    @Override
    public JSONObject addDetail(VillageDetailParams villageDetailParams) {
        VillageDetailModel one = getOne(Wrappers.lambdaQuery(new VillageDetailModel())
                .eq(VillageDetailModel::getIsDelete, false)
                .eq(VillageDetailModel::getVillageId, villageDetailParams.getVillageId())
                .eq(VillageDetailModel::getUserId, villageDetailParams.getUserId())
                .eq(VillageDetailModel::getName, villageDetailParams.getKey())
                .last("limit 1")
        );
        if (Objects.isNull(one)) {
            one = new VillageDetailModel();
            one.setName(villageDetailParams.getKey());
            one.setVillageId(villageDetailParams.getVillageId());
            one.setUserId(villageDetailParams.getUserId());
            one.setValue(NumberUtil.yuanToFen(villageDetailParams.getValue()));
            if (!save(one)) {
                log.error("添加类目失败,要添加的信息是[{}]",JSONObject.toJSONString(one));
                throw new EleException("添加类目失败");
            }
        }else {
            one.setValue(NumberUtil.yuanToFen(villageDetailParams.getValue()));
            if (!updateById(one)) {
                log.error("修改类目失败,要添加的信息是[{}]",JSONObject.toJSONString(one));
                throw new EleException("添加类目失败");
            }
        }
        return R.success(one);
    }

    @Override
    public VillageDetailModel getDetailById( Long detailId) {
        return getOne(Wrappers.lambdaQuery(new VillageDetailModel())
                .eq(VillageDetailModel::getIsDelete, false)
                .eq(VillageDetailModel::getId, detailId)
                .last("limit 1")
        );
    }

    @Override
    public VillageDetailModel getDetailByIdIncludeDeleted(Long detailId) {
        return getById(detailId);
    }
}
